package com.liwei.lwmail.elasticsearch.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.liwei.common.to.es.SkuEsModel;
import com.liwei.common.utils.R;
import com.liwei.lwmail.elasticsearch.config.ElasticSearchConfig;
import com.liwei.lwmail.elasticsearch.constant.EsConstant;
import com.liwei.lwmail.elasticsearch.feign.ProductFeignService;
import com.liwei.lwmail.elasticsearch.service.MallSearchService;
import com.liwei.lwmail.elasticsearch.vo.AttrResponseVo;
import com.liwei.lwmail.elasticsearch.vo.BrandVo;
import com.liwei.lwmail.elasticsearch.vo.SearchParam;

import com.liwei.lwmail.elasticsearch.vo.SearchResult;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service("mallSearchService")
public class MallSearchServiceImpl implements MallSearchService {

    @Autowired
    private RestHighLevelClient client;
    @Autowired
    private ProductFeignService productFeignService;

    @Override
    public SearchResult search(SearchParam searchParam, HttpServletRequest request) {
        //动态构建DSL
        SearchResult result = null;
        //1、准备检索请求
        SearchRequest searchRequest = buildSearchRequest(searchParam);
        try {
            //2、执行检索
            SearchResponse searchResponse = client.search(searchRequest, ElasticSearchConfig.COMMON_OPTIONS);

            //3、分析响应数据，封装成需要的格式
            result = buildSearchResult(searchResponse,searchParam,request);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 构建检索请求
     * 模糊匹配、过滤(属性、分类、品牌、价格区间、库存)、排序、分页、高亮、聚合分析
     * @return
     */
    private SearchRequest buildSearchRequest(SearchParam param) {
        SearchSourceBuilder builder = new SearchSourceBuilder();//构建DSL语句
        /**
         * 1、模糊匹配、过滤(属性、分类、品牌、价格区间、库存)
         */
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //1.1 must 模糊匹配
        if (!StringUtils.isEmpty(param.getKeyword())){
            boolQuery.must(QueryBuilders.matchQuery("skuTitle",param.getKeyword()));
        }
        //1.2 filter 过滤(分类、品牌、库存、价格区间、属性)
        if (param.getCatalog3Id() != null){
            boolQuery.filter(QueryBuilders.termQuery("catalogId",param.getCatalog3Id()));
        }
        if (param.getBrandId() != null && param.getBrandId().size()>0){
            boolQuery.filter(QueryBuilders.termsQuery("brandId",param.getBrandId()));
        }
        if (param.getHasStock() != null){
            boolQuery.filter(QueryBuilders.termQuery("hasStock",param.getHasStock()==1));
        }
        if (!StringUtils.isEmpty(param.getSkuPrice())){
            //2000_5000/_5000/5000_
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String[] s = param.getSkuPrice().split("_");
            if (s.length == 2){
                rangeQuery.gte(s[0]).lte(s[1]);
            }else if (s.length == 1){
                if (param.getSkuPrice().startsWith("_")){
                   rangeQuery.lte(s[0]);
                }else {
                    rangeQuery.gte(s[0]);
                }
            }
            boolQuery.filter(rangeQuery);
        }
        if (param.getAttrs() != null && param.getAttrs().size()>0){

            for (String attr : param.getAttrs()) {
                BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();
                //attr=1_8寸:10寸
                String[] s = attr.split("_");

                String attrId = s[0];//检索的属性id
                String[] attrValues = s[1].split(":");
                nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId",attrId));
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue",attrValues));
                //每一个必须都得生成嵌入式的查询
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedBoolQuery, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }
        }

        builder.query(boolQuery);

        /**
         * 2、排序、分页、高亮
         */
        if (!StringUtils.isEmpty(param.getSort())){
            //sort=hotScore_asc/desc
            String[] s = param.getSort().split("_");
            SortOrder order = s[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            builder.sort(s[0], order);
        }
        //分页
        builder.from((param.getPage()-1)*EsConstant.PRODUCT_PAGE_SIZE);
        builder.size(EsConstant.PRODUCT_PAGE_SIZE);
        //高亮
        if (!StringUtils.isEmpty(param.getKeyword())){
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            builder.highlighter(highlightBuilder);
        }

        /**
         * 聚合分析
         */
        //1、品牌聚合
        TermsAggregationBuilder brandAgg = AggregationBuilders.terms("brandAgg").field("brandId").size(50);

        //2、品牌的两个子聚合
        brandAgg.subAggregation(AggregationBuilders.terms("brandNameAgg").field("brandName").size(1));
        brandAgg.subAggregation(AggregationBuilders.terms("brandImgAgg").field("brandImg").size(1));
        builder.aggregation(brandAgg);

        //3、分类聚合
        TermsAggregationBuilder catalogAgg = AggregationBuilders.terms("catalogAgg").field("catalogId").size(20);
        catalogAgg.subAggregation(AggregationBuilders.terms("catalogNameAgg").field("catalogName").size(1));
        builder.aggregation(catalogAgg);

        //4、属性聚合
        NestedAggregationBuilder nested = AggregationBuilders.nested("attrsAgg", "attrs");
        TermsAggregationBuilder attrIdAgg = AggregationBuilders.terms("attrIdAgg").field("attrs.attrId");
        //聚合属性id下的属性名
        attrIdAgg.subAggregation(AggregationBuilders.terms("attrNameAgg").field("attrs.attrName").size(1));
        //聚合属性id下的所有属性值
        attrIdAgg.subAggregation(AggregationBuilders.terms("attrValueAgg").field("attrs.attrValue").size(50));
        nested.subAggregation(attrIdAgg);
        builder.aggregation(nested);

        return new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, builder);
    }

    /**
     * 封装结果数据
     * @return
     */
    private SearchResult buildSearchResult(SearchResponse searchResponse,SearchParam searchParam, HttpServletRequest request) {
        SearchResult result = new SearchResult();
        //1、查询到的所有商品
        List<SkuEsModel> products = new ArrayList<>();
        SearchHits hits = searchResponse.getHits();
        if (hits.getHits() != null && hits.getHits().length > 0){
            for (SearchHit hit : hits.getHits()) {
                String source = hit.getSourceAsString();
                SkuEsModel esModel = new SkuEsModel();
                SkuEsModel skuEsModel = JSON.parseObject(source, esModel.getClass());
                if (!StringUtils.isEmpty(searchParam.getKeyword())){
                    //设置高亮
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String skuTitleHighLight = skuTitle.getFragments()[0].string();
                    skuEsModel.setSkuTitle(skuTitleHighLight);
                }
                products.add(skuEsModel);
            }
        }
        result.setProducts(products);

        //2、当前所有商品涉及到的所有属性信息
        List<SearchResult.AttrVo> attrs = new ArrayList<>();
        ParsedNested attrsAgg = searchResponse.getAggregations().get("attrsAgg");
        ParsedLongTerms attrIdAgg = attrsAgg.getAggregations().get("attrIdAgg");
        for (Terms.Bucket bucket : attrIdAgg.getBuckets()) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            //属性id
            attrVo.setAttrId(Long.parseLong(bucket.getKeyAsString()));
            //属性name
            ParsedStringTerms attrNameAgg = bucket.getAggregations().get("attrNameAgg");
            attrVo.setAttrName(attrNameAgg.getBuckets().get(0).getKeyAsString());
            //属性value
            ParsedStringTerms attrValueAgg = bucket.getAggregations().get("attrValueAgg");
            List<String> attrValue = attrValueAgg.getBuckets().stream().map(item -> {
                return item.getKeyAsString();
            }).collect(Collectors.toList());

            attrVo.setAttrValue(attrValue);
            attrs.add(attrVo);
        }
        result.setAttrs(attrs);

        //3、当前商品涉及到的品牌信息
        List<SearchResult.BrandVo> brands = new ArrayList<>();
        ParsedLongTerms brandAgg = searchResponse.getAggregations().get("brandAgg");
        for (Terms.Bucket bucket : brandAgg.getBuckets()) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            //品牌id
            brandVo.setBrandId(Long.parseLong(bucket.getKeyAsString()));
            //品牌name
            ParsedStringTerms brandNameAgg = bucket.getAggregations().get("brandNameAgg");
            brandVo.setBrandName(brandNameAgg.getBuckets().get(0).getKeyAsString());
            //品牌img
            ParsedStringTerms brandImgAgg = bucket.getAggregations().get("brandImgAgg");
            brandVo.setBrandImg(brandImgAgg.getBuckets().get(0).getKeyAsString());

            brands.add(brandVo);
        }
        result.setBrands(brands);

        //4、当前商品涉及到的所有分类信息
        List<SearchResult.CatalogVo> catalogs = new ArrayList<>();
        ParsedLongTerms catalogAgg = searchResponse.getAggregations().get("catalogAgg");
        for (Terms.Bucket bucket : catalogAgg.getBuckets()) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();

            //分类id
            String key = bucket.getKeyAsString();
            catalogVo.setCatalogId(Long.parseLong(key));

            //分类名
            ParsedStringTerms catalogNameAgg = bucket.getAggregations().get("catalogNameAgg");
            String catalogName = catalogNameAgg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(catalogName);

            catalogs.add(catalogVo);
        }
        result.setCatalogs(catalogs);

//        ================以上从聚合信息中获取到================

        //5、分页信息
        Integer page = searchParam.getPage();
        result.setPage(page);

        long total = hits.getTotalHits().value;
        result.setTotal(total);

        int totalPages = (int) (total%EsConstant.PRODUCT_PAGE_SIZE == 0?total/EsConstant.PRODUCT_PAGE_SIZE:total/EsConstant.PRODUCT_PAGE_SIZE+1);
        result.setTotalPages(totalPages);

        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 1;i <=totalPages;i++){
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);

        //6、构建面包屑导航功能
        if (searchParam.getAttrs() != null && searchParam.getAttrs().size() > 0){
            List<SearchResult.NavVo> navs = searchParam.getAttrs().stream().map(attr->{
                //分析查询参数
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                String[] s = attr.split("_");
                navVo.setNavValue(s[1]);

                long attrId = Long.parseLong(s[0]);
                result.getAttrIds().add(attrId);
                R r = productFeignService.getAttrInfo(attrId);
                if (r.getCode() == 0){
                    AttrResponseVo attrResponseVo = r.getData("attr", new TypeReference<AttrResponseVo>() {});
                    navVo.setNavName(attrResponseVo.getAttrName());
                }else {
                    navVo.setNavName(s[0]);
                }
                //取消了面包屑以后，我们要跳转到哪个地方,将请求url当前值指控
                String replace = replaceQueryString(searchParam, attr, "attrs", request);
                navVo.setLink("http://search.lwmall.com/list.html?"+replace);

                return navVo;
            }).collect(Collectors.toList());

            result.setNavs(navs);
        }

        //品牌分类
        if(searchParam.getBrandId()!=null && searchParam.getBrandId().size()>0){
            List<SearchResult.NavVo> navs = result.getNavs();
            SearchResult.NavVo navVo = new SearchResult.NavVo();
            navVo.setNavName("品牌");

            R r = productFeignService.brandInfos(searchParam.getBrandId());
            if (r.getCode()==0){
                List<BrandVo> brandVos = r.getData("brands", new TypeReference<List<BrandVo>>() {});
                StringBuffer buffer = new StringBuffer();
                String replace = "";
                for (BrandVo brandVo : brandVos) {
                    buffer.append(brandVo.getName()+";");
                    replace = replaceQueryString(searchParam, brandVo.getBrandId()+"", "brandId", request);
                }
                navVo.setNavValue(buffer.toString());
                navVo.setLink("http://search.lwmall.com/list.html?"+replace);
            }
            navs.add(navVo);
            result.setNavs(navs);
        }
        //TODO 分类：不需要导航取消

        return result;
    }

    private String replaceQueryString(SearchParam searchParam, String value, String key, HttpServletRequest request) {
        String encode = null;
        try {
            encode = URLEncoder.encode(value, "UTF-8");
            encode = encode.replace("+","%20");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //TODO 有问题第一个参数开头是?,无法replace成功
        String replace = searchParam.get_queryString().replace("&"+key+"=" + encode, "");
        return replace;
    }
}
